package bootstrap

import (
	"os"

	"go.uber.org/zap"
	"go.uber.org/zap/zapcore"
	"gopkg.in/natefinch/lumberjack.v2"
	"ttsx/server/common/global"
	"ttsx/server/utils"
)

var (
	level   zapcore.Level // zap 日志等级
	options []zap.Option  // zap 配置项目
)

func InitLog() *zap.Logger {
	// 创建log目录
	if ok, _ := utils.PathExists(global.App.Config.Log.LogsPath); !ok {
		_ = os.Mkdir(global.App.Config.Log.LogsPath, os.ModePerm)
	}

	// 设置日志等级
	setLogLevel()

	// 判断日志是否显示行号
	if global.App.Config.Log.ShowLine {
		options = append(options, zap.AddCaller())
	}

	// 初始化日志
	encoderConfig := zap.NewProductionEncoderConfig()
	encoderConfig.EncodeTime = zapcore.ISO8601TimeEncoder
	encoderConfig.EncodeLevel = zapcore.CapitalLevelEncoder

	encode := zapcore.NewConsoleEncoder(encoderConfig) // 按普通文本方式写日志文件

	fs := zapcore.AddSync(&lumberjack.Logger{
		Filename:   global.App.Config.Log.LogsPath + "/" + global.App.Config.Log.Filename,
		MaxBackups: global.App.Config.Log.MaxBackups,
		MaxSize:    global.App.Config.Log.MaxSize,
		MaxAge:     global.App.Config.Log.MaxAge,
		Compress:   global.App.Config.Log.Compress,
	})

	code := zapcore.NewCore(encode, fs, level)

	return zap.New(code, options...)
}

func setLogLevel() {
	switch global.App.Config.Log.Level {
	case "debug":
		level = zapcore.DebugLevel
		options = append(options, zap.AddStacktrace(level))
	case "info":
		level = zap.InfoLevel
	case "warn":
		level = zap.WarnLevel
	case "error":
		level = zap.ErrorLevel
		options = append(options, zap.AddStacktrace(level))
	case "dpanic":
		level = zap.DPanicLevel
	case "panic":
		level = zap.PanicLevel
	case "fatal":
		level = zap.FatalLevel
	default:
		level = zap.InfoLevel
	}
}
